const express=require('express')
const mongoose=require('mongoose')
const bodyParser=require('body-parser')
const app=express()
mongoose.connect('mongodb://127.0.0.1:27017/sw',{useNewUrlParser:true,useUnifiedTopology:true})
const db=mongoose.connection;
db.on('error',console.error.bind(console,'MongoDB连接错误'))
const dataSchema=new mongoose.Schema({type:String,money:Number,date:{type:Date,default:Date.now},useFor:String})
const DataModel=mongoose.model('Data',dataSchema)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.use(require('cors')())
app.post('/api/save-data',async(req,res)=>{
  try{
    const newData=new DataModel(req.body)
    await newData.save()
    res.send('数据提交成功')
  }catch(error){
    res.status(500).json({error:'服务器错误'})
  }
})
const PORT=3001;
app.listen(PORT,()=>{
  console.log(`服务器运行在http://localhost:${PORT}`);
})